package cn.chench.config;

import java.util.concurrent.Callable;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy;

/**
 * 创建一个自定义的hystrix 线程策略, 将servletRequestAttributes传入新线程中，并赋给RequestContextHolder:
 * @author chencaihui
 * @datetime 创建时间：2020年11月18日 上午11:57:32
 */
public class FeignHystrixConcurrencyStrategy extends HystrixConcurrencyStrategy {
	
	@Override
	public <T> Callable<T> wrapCallable(Callable<T> callable) {
		ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		return new Callable<T>() {
			@Override
			public T call() throws Exception {
				try {
					if (null != servletRequestAttributes) {
						RequestContextHolder.setRequestAttributes(servletRequestAttributes);
					}
					return callable.call();
				} finally {
					RequestContextHolder.resetRequestAttributes();
				}
			}
		};
	}

}
